package com.change.core.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;

/**
 * DateSerializer
 *
 * @author linqunxun
 * @date 2021/9/10 10:24 上午
 */
public class DateSerializer extends StdSerializer<Date> {

    private static DateFormat DATE_TIME_FORMAT = DateFormat.getDateTimeInstance();

    public DateSerializer(){
        super(Date.class);
    }

    @Override
    public void serialize(Date value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (value != null) {
            if(provider.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)) {
                gen.writeNumber(value.getTime());
            }else {
                gen.writeString(DATE_TIME_FORMAT.format(value));
            }
        } else {
            gen.writeNull();
        }
    }
}
